package server;

import server.connector.http.*;

import javax.servlet.Servlet;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;

public class ServletProcessor {
    //类加载器
    private static final URLClassLoader LOADER;
    static {
        String repository = "file:" + Constants.WEB_ROOT + File.separator;
        URL[] urls = new URL[1];
        URLStreamHandler streamHandler = null;
        try {
            urls[0] = new URL(null, repository, streamHandler);
        } catch (MalformedURLException e) {
            System.out.println("servlet加载器初始化出错");
            e.printStackTrace();
        }
        LOADER = new URLClassLoader(urls);
    }
    public void process(HttpRequest request, HttpResponse response) {
        String uri = request.getRequestURI();
        String servletName = uri.substring(uri.lastIndexOf('/') + 1);
        try {
            Class servletClass = LOADER.loadClass(servletName);
            Servlet servlet = (Servlet)servletClass.newInstance();
            HttpRequestFacade httpRequestFacade = new HttpRequestFacade(request);
            HttpResponseFacade httpResponseFacade = new HttpResponseFacade(response);
            servlet.service(httpRequestFacade, httpResponseFacade);
            response.finishResponse();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
